package com.example.sunmiv1.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.DepositGoodsEditInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class EditDepositAdapter extends BaseAdapter {

    private Context context;
    private ViewHolder viewHolder;
    private List<DepositGoodsEditInfo.DataBean> list;
    //    private int type;//  0|2 PurchaseOrderAddActivity採購單添加  1|3編輯   此處無用
    private String pricePermission;// 門店查看價格權限
    private ACache aCache;

    public EditDepositAdapter(Context context, List<DepositGoodsEditInfo.DataBean> list) {
        this.context = context;
        this.list = list;
        aCache = ACache.get(context);
        pricePermission = aCache.getAsString("showPrice");
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView = View.inflate(context, R.layout.add_deposit_adapter, null);
        viewHolder = new ViewHolder(convertView);
        viewHolder.addDepositCheck.setVisibility(View.GONE);
        viewHolder.addDepositName.setText(list.get(position).getGoods_name());
        viewHolder.addDepositFreightNumber.setText(list.get(position).getGoods_number());
        viewHolder.addDepositCode.setText(list.get(position).getGoods_code());

        Tools.hideViewInItem(list.get(position).getSku_name(), viewHolder.infoSkuName);

        viewHolder.addDepositTvStock.setText(R.string.QuantityOperated);
        viewHolder.addDepositStock.setText(list.get(position).getOperated_num() + "");
        if ("2".equals(aCache.getAsString("modify_price_state"))) {
            ((View) viewHolder.depositGoodsRetailPrice.getParent()).setVisibility(View.VISIBLE);
            ((View) viewHolder.depositGoodsOnlinePrice.getParent()).setVisibility(View.VISIBLE);
        } else {
            ((View) viewHolder.depositGoodsRetailPrice.getParent()).setVisibility(View.GONE);
            ((View) viewHolder.depositGoodsOnlinePrice.getParent()).setVisibility(View.GONE);
        }
        viewHolder.depositGoodsRetailPrice.setText(list.get(position).getRetail_price());
        viewHolder.depositGoodsOnlinePrice.setText(list.get(position).getOnline_price());
        if ("2".equals(list.get(position).getPricing_method())) {//稱重商品
            viewHolder.addDepositNum.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        } else {
            viewHolder.addDepositNum.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
        }
//        viewHolder.addDepositUnit.setText(list.get(position).getCompany());

        Tools.hideViewInItem(list.get(position).getCompany(), viewHolder.addDepositUnit);
        final EditText edit = viewHolder.addDepositPrice;
        if (0 < list.get(position).getOperated_num()) {
            edit.setEnabled(true);
        } else {
            edit.setEnabled(false);
        }
        viewHolder.addDepositTvPrice.setText(R.string.PurchasePrice);
        edit.setText(list.get(position).getPurchase_price() + "");
        final TextWatcher adtpTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                limitDecimal(charSequence, viewHolder.addDepositPrice);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.addDepositPrice.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        list.get(position).setPurchase_price(Double.valueOf(s.toString().trim()));
                    } else {
                        list.get(position).setPurchase_price(0.0);
                    }
                }
            }
        };
        setETFocusChangeListener(position, adtpTextWatcher, edit);


        viewHolder.addDepositTvNum.setText(R.string.PurchaseQuantity);
        viewHolder.addDepositNum.setText(list.get(position).getPurchase_num() + "");


        final TextWatcher adnTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                limitDecimal(charSequence, viewHolder.addDepositNum);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.addDepositNum.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        list.get(position).setPurchase_num(Double.valueOf(s.toString().trim()));
                    } else {
                        list.get(position).setPurchase_num(0.0);
                    }
                }
            }
        };
        setETFocusChangeListener(position, adnTextWatcher, viewHolder.addDepositNum);
        viewHolder.addDepositQualityGuaranteePeriod.setEnabled(false);

        viewHolder.addDepositRemark.setText(list.get(position).getRemarks());
        final TextWatcher rmkTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.addDepositRemark.hasFocus()) {
                    list.get(position).setRemarks(s.toString().trim());
                }
            }
        };
        setETFocusChangeListener(position, rmkTextWatcher, viewHolder.addDepositRemark);

        if ("2".equals(pricePermission)) {
            ((View) viewHolder.addDepositPrice.getParent()).setVisibility(View.GONE);
        }
        if ("1".equals(list.get(position).getSerial_number_state())) {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            viewHolder.addDepositNum.setVisibility(View.GONE);
            Log.e("TAG", "onBindViewHolder: 商品的庫存========" + list.get(position).getPurchase_num());
            viewHolder.inventorySearchAdapterInventoryTv.setText(list.get(position).getPurchase_num() + "");
        } else {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            viewHolder.addDepositNum.setVisibility(View.VISIBLE);
        }
        viewHolder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(position);
            }
        });
        return convertView;
    }


    /**
     * 限制小數點後三位
     *
     * @param charSequence str
     * @param et           et
     */
    private void limitDecimal(CharSequence charSequence, EditText et) {
        LogUtil.i("onTextChanged: charSequence=" + charSequence.toString());
        if (charSequence.toString().contains(".")) {
            if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                et.setText(charSequence.toString().
                        substring(0, charSequence.toString().length() - 1));
                et.setSelection(charSequence.length() - 1);
            } else {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                    charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                    et.setText(charSequence);
                    et.setSelection(charSequence.length());
                }
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            et.setText(charSequence);
            et.setSelection(2);
        }

        if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                et.setText(charSequence.subSequence(1, 2));
                et.setSelection(1);
            }
        }
    }

    /**
     * 設置edittext焦點的監聽器
     *
     * @param position    pos
     * @param textWatcher watcher
     * @param editText    et
     */
    private void setETFocusChangeListener(int position, TextWatcher textWatcher, EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                ((EditText) v).addTextChangedListener(textWatcher);
                Log.e("addTextChanged", position + "");
            } else {
                ((EditText) v).removeTextChangedListener(textWatcher);
                Log.e("removeTextChanged", position + "");
            }
        });
    }

    private Choose choose;

    public void setChoose(Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index);
    }

    static class ViewHolder {
        @BindView(R.id.addDeposit_check)
        CheckBox addDepositCheck;
        @BindView(R.id.addDeposit_name)
        TextView addDepositName;
        @BindView(R.id.info_sku_name)
        TextView infoSkuName;
        @BindView(R.id.layout_sku_name)
        RelativeLayout layoutSkuName;
        @BindView(R.id.addDeposit_freightNumber)
        TextView addDepositFreightNumber;
        @BindView(R.id.addDeposit_code)
        TextView addDepositCode;
        @BindView(R.id.addDeposit_tvStock)
        TextView addDepositTvStock;
        @BindView(R.id.addDeposit_stock)
        TextView addDepositStock;
        @BindView(R.id.addDeposit_tvUnit)
        TextView addDepositTvUnit;
        @BindView(R.id.addDeposit_unit)
        TextView addDepositUnit;
        @BindView(R.id.addDeposit_build_date)
        TextView addDepositBuildDate;
        @BindView(R.id.addDeposit_quality_guarantee_period)
        EditText addDepositQualityGuaranteePeriod;
        @BindView(R.id.addDeposit_tvPrice)
        TextView addDepositTvPrice;
        @BindView(R.id.addDeposit_price)
        EditText addDepositPrice;
        @BindView(R.id.depositGoods_retailPrice)
        EditText depositGoodsRetailPrice;
        @BindView(R.id.depositGoods_onlinePrice)
        EditText depositGoodsOnlinePrice;
        @BindView(R.id.addDeposit_tvNum)
        TextView addDepositTvNum;
        @BindView(R.id.addDeposit_num)
        EditText addDepositNum;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.addDeposit_remark)
        EditText addDepositRemark;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
